
import { reqGetUserDetaIlById, reqGetUserInfo, reqLogin } from '@/api/user'
import { getToken, setToken, removeToken } from '@/utils/auth'
import { resetRouter } from '@/router'
export default {
  state() {
    return {
      token: getToken() || '',
      userInfo: {}
    }
  },
  mutations: {
    setToken(state, newToken) {
      // vuex持久化
      state.token = newToken
      // 本地储存持久化
      setToken(newToken)
    },
    setUserInfo(state, NewUserInfo) {
      state.userInfo = NewUserInfo
    },
    removeToken(state) {
      state.token = ''
      removeToken()
    },
    removeUserInfo(state) {
      state.userInfo = {}
    },
    setStaffPhoto(state, photo) {
      state.userInfo.staffPhoto = photo
    }
  },
  actions: {
    async login(context, loginFrom) {
      const res = await reqLogin(loginFrom)
      // console.log('5555', res.data)
      const token = res.data
      context.commit('setToken', token)
    },
    async getUserInfo(context) {
      // console.log('3333', context)
      const { data: data1 } = await reqGetUserInfo()
      // console.log('99', data)
      const { data: data2 } = await reqGetUserDetaIlById(data1.userId)
      // const res = { ...data1, ...data2 }
      // 第二种写法
      const res = Object.assign(data1, data2)
      context.commit('setUserInfo', res)
      return res
    },
    logout({ commit }) {
      commit('removeToken')
      commit('removeUserInfo')
      resetRouter()
      commit('permission/setRoutes', [], { root: true })
    },
    setStaffPhoto({ commit }, url) {
      commit('setStaffPhoto', url)
    }
  },
  getters: {},
  namespaced: true
}
